/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIManager.java
 *
 * Created on 15-Jan-2009, 22:44:13
 */

package gride.gui;

import gride.events.EventManager;
import gride.events.GrideEvents;
import gride.exceptions.UserCancelException;
import java.awt.Component;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

/**
 *
 * @author lukasz
 */
public class GUIManager extends javax.swing.JFrame
{

    // <editor-fold defaultstate="expanded" desc="Static Fields">

    /**
     *
     */
    public static final int RIGHT_PANE = 0;
    /**
     *
     */
    public static final int BOTTOM_PANE = 1;
    /**
     *
     */
    public static final int MAIN_PANE = 2;

    // </editor-fold>

    
    // <editor-fold defaultstate="expanded" desc="Members">

    private EventManager eventManager;

    // </editor-fold>



    // <editor-fold defaultstate="expanded" desc="Constuctors">

    /**
     *
     * @param eventManager
     */
    public GUIManager(EventManager eventManager)
    {
        super("Gride");

        initComponents();

        jSplitPane1.addComponentListener(new ComponentAdapter() {

            public void componentResized(ComponentEvent e) {
                jSplitPane1.setDividerLocation(0.80);
            }

            public void componentShown(ComponentEvent e) 
            {
                jSplitPane1.setDividerLocation(0.80);
            }
        });

        jSplitPane2.addComponentListener(new ComponentAdapter() {

            public void componentResized(ComponentEvent e) {
                jSplitPane2.setDividerLocation(0.70);
            }

            public void componentShown(ComponentEvent e) {
                jSplitPane2.setDividerLocation(0.70);
            }
        });
       
        setExtendedState(MAXIMIZED_BOTH);

        this.eventManager = eventManager;
    }

    // </editor-fold>


    // <editor-fold defaultstate="expanded" desc="Public Methods">

    /**
     *
     * @param panel
     * @param component
     * @param title
     */
    public void addComponent(int panel, final JComponent component,
                             String title)
    {
        switch(panel)
        {
            case RIGHT_PANE:
                rightTabbedPane.addTab(title, component);
                //rightTabbedPane.setSelectedComponent(component);
                break;

            case BOTTOM_PANE:
                
                bottomTabbedPane.addTab(title, component);
                //bottomTabbedPane.setSelectedComponent(component);
                break;

            case MAIN_PANE:
                // create an internal frame with the component
                JInternalFrame frame = new JInternalFrame(title, true, true,
                                                          true, true);
                frame.setSize(500, 300);
                frame.add(component);                
                
                // add the frame to the main panel and make it visible
                mainPane.add(frame);
                frame.moveToBack();
                frame.setVisible(true);

                // arrange all frames
                int x = 0;
                int y = 0;
                int xInc = mainPane.getWidth() / mainPane.getAllFrames().length;
                int yInc = mainPane.getHeight() /mainPane.getAllFrames().length;

                for (JInternalFrame f : mainPane.getAllFrames())
                {
                    f.setBounds(x, y, 500, 300);
                    x += xInc;
                    y += yInc;
                }
                                
                break;
        }
    }


    // removes the gives component from the GUI, looking for it
    // in the rightPane, bottomPane tabs, as well as mainPane frames
    /**
     *
     * @param component
     */
    public void removeComponent(Component component)
    {
        // check each pane if the component is there
        rightTabbedPane.remove(component);
        bottomTabbedPane.remove(component);

        // for main pane we need to look inside each internal frame to see
        // if it contains the component we want to remove
        for (JInternalFrame frame : mainPane.getAllFrames())
            if (frame.getContentPane().getComponent(0) == component)
            {
                frame.dispose();
                return;
            }
    }


    // locates the given component amongst all available panes and
    // tries to bring it up (select the tab, etc)
    /**
     *
     * @param component
     */
    public void focusOnComponent(Component component)
    {
        // check in each pane
        try
        {
            rightTabbedPane.setSelectedComponent(component);
        }
        catch (IllegalArgumentException e)
        { }

        try 
        {
            bottomTabbedPane.setSelectedComponent(component);
        }
        catch (IllegalArgumentException e)
        { }

        // for main pane we need to look inside each internal frame to see
        // if it contains the component we want to focus on
        for (JInternalFrame frame : mainPane.getAllFrames())
            if (frame.getContentPane().getComponent(0) == component)
            {
                frame.moveToFront();
                frame.requestFocus();
                return;
            }
    }


    // adds the given menu item to a menu with the specified name
    // if such a menu doesn't exist, it will be created
    /**
     *
     * @param item
     * @param menuName
     */
    public void addMenuItem(JMenuItem item, String menuName)
    {
        // remove the menuitems we want at the end of their menus
        fileMenu.remove(exitMenuItem);
        helpMenu.remove(aboutMenuItem);

        JMenu menu = null;
        
        // check if such a menu already exists
        for (int i=0; i<menuBar.getMenuCount(); i++)
        {
            if (menuBar.getMenu(i).getText().equals(menuName))
                menu = menuBar.getMenu(i);
        }
        
        // if there's no such menu yet, create one and add to the menubar
        if (menu == null)
        {
            menu = new JMenu(menuName);

            // add to menubar, but leaving Help menu last
            menuBar.remove(helpMenu);
            menuBar.add(menu);
            menuBar.add(helpMenu);
        }

        // add the given item
        menu.add(item);

        // replace the items we removed in the first place
        fileMenu.add(exitMenuItem);
        helpMenu.add(aboutMenuItem);
    }


    // goes through all menus and removes the given item if it finds it
    /**
     * 
     * @param item
     */
    public void removeMenuItem(JMenuItem item)
    {
        for (int i=0; i<menuBar.getMenuCount(); i++)
        {
            menuBar.getMenu(i).remove(item);

            // if there are no items left in this menu, remove it
            if (menuBar.getMenu(i).getItemCount() == 0)
                menuBar.remove(i);

            menuBar.invalidate();
        }
    }


    // </editor-fold>



    // <editor-fold defaultstate="expanded" desc="Private Methods">

    private void exitAction()
    {
        if (JOptionPane.showConfirmDialog(null, 
                       "Are you sure you want to exit Gride?", "Exit",
                       JOptionPane.YES_NO_OPTION,
                       JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION)
            return;

        try
        {
            eventManager.raiseEvent(GrideEvents.EXITING_GRIDE, null);
            this.dispose();
            System.exit(0);
        }
        catch (UserCancelException e)
        {
            System.out.println("User cancelled");
        }
    }

    // </editor-fold>


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jSeparator1 = new javax.swing.JSeparator();
        jSplitPane1 = new javax.swing.JSplitPane();
        jSplitPane2 = new javax.swing.JSplitPane();
        mainPane = new javax.swing.JDesktopPane();
        bottomTabbedPane = new javax.swing.JTabbedPane();
        rightTabbedPane = new javax.swing.JTabbedPane();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        exitMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        aboutMenuItem = new javax.swing.JMenuItem();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jSplitPane1.setDividerLocation(689);
        jSplitPane1.setDividerSize(8);
        jSplitPane1.setResizeWeight(1.0);

        jSplitPane2.setDividerLocation(324);
        jSplitPane2.setDividerSize(8);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane2.setResizeWeight(1.0);
        jSplitPane2.setTopComponent(mainPane);

        bottomTabbedPane.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        jSplitPane2.setRightComponent(bottomTabbedPane);

        jSplitPane1.setLeftComponent(jSplitPane2);
        jSplitPane1.setRightComponent(rightTabbedPane);

        fileMenu.setText("File");

        exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText("Help");

        aboutMenuItem.setText("About...");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 861, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        exitAction();
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        exitAction();
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JTabbedPane bottomTabbedPane;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JDesktopPane mainPane;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTabbedPane rightTabbedPane;
    // End of variables declaration//GEN-END:variables

}
